<template>
  <div>
    <div style=" text-align: right;">
      <el-select size="small" class="goods-search" v-model="type" @change="change">
        <el-option value="价格" label="价格"></el-option>
        <el-option value="种类" label="种类"></el-option>
        <el-option value="商品名" label="商品名"></el-option>
      </el-select>
      <div style=" display:inline-block;" v-if="type==='价格'">
        <input
            type="text"
            placeholder="¥"
            v-model.number="money1"
            size="small"
            class="el-input__inner inputwidth"
            oninput="value=value.replace(/[^\d]/g,'');if(value.length>10)value=value.slice(0,10)"
        />
        <span style="margin-left:5px;margin-right:5px;">-</span>
        <input
            type="text"
            placeholder="¥"
            v-model.number="money2"
            size="small"
            class="el-input__inner inputwidth"
            oninput="value=value.replace(/[^\d]/g,'');if(value.length>10)value=value.slice(0,10)"
        />
      </div>

      <el-select size="small" class="width200" v-model="searchVal" v-else-if="type==='种类'" clearable>
        <el-option value="狗粮" label="狗粮"></el-option>
        <el-option value="猫粮" label="猫粮"></el-option>
        <el-option value="猪粮" label="猪粮"></el-option>
        <el-option value="玩具" label="玩具"></el-option>
        <el-option value="日用品" label="日用品"></el-option>
        <el-option value="颈链" label="颈链"></el-option>
        <el-option value="洗浴" label="洗浴"></el-option>
        <el-option value="医疗" label="医疗"></el-option>
        <el-option value="睡窝" label="睡窝"></el-option>
        <el-option value="宠物箱" label="宠物箱"></el-option>
      </el-select>

      <el-input v-model="searchVal" v-else size="small" class="width200" clearable></el-input>
      <el-button type="primary" size="small" style="margin-left:10px;" @click="goSearch">搜索</el-button>
    </div>

    <el-row style="min-width:1120px;max-width:1350px;width:100%" v-if="tableData.length!==0">
      <el-col :span="4" v-for="(item, index) in tableData" :key="index">
        <el-card class="goods-card" shadow="hover" :body-style="{ padding: '0px' }">
          <el-image class="goods-image" :src="item.picture"></el-image>
          <div>
            <span class="goods-money">¥ {{item.price}}元</span>
            <span class="goods-num">{{item.num}}件</span>
            <el-tooltip
                v-if="item.name.length>12"
                class="goods-title"
                effect="dark"
                :content="item.name"
                placement="top"
            >
              <p class="goods-title">{{item.name}}</p>
            </el-tooltip>
            <p v-else class="goods-title">{{item.name}}</p>
            <div class="goods-button-box">
              <el-button
                  v-if="item.collect"
                  type="danger"
                  size="small"
                  icon="el-icon-star-off"
                  @click="goNoCollect(item)"
              ></el-button>
              <el-button v-else size="small" icon="el-icon-star-off" plain @click="goCollect(item)"></el-button>
              <el-button
                  type="primary"
                  size="mini"
                  plain
                  icon="el-icon-shopping-cart-1"
                  @click="goAddShop(item)"
              ></el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="box-card goods-card-box" v-else>
      <div slot="header" class="clearfix">
        <span>告示</span>
      </div>
      <p>暂无符合搜索要求的商品</p>
    </el-card>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageNo+1"
        :page-sizes="[12,24,36,48]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        class="fyclass"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  name: "goods",
  data() {
    return {
      type: "价格",
      searchVal: "狗粮",
      money1: "",
      money2: "",
      total: 0,
      pageNo: 0,
      pageSize: 12,
      tableData: [],
      collectObs: []
    };
  },
  created() {
    this.goQuery();
  },
  methods: {
    makePendingQuery() {
      let query = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        status: "saling",
        show: true
      };
      if (this.type === "价格") {
        if (this.money1 !== "" && this.money2 == "") {
          query.small = this.money1;
        } else if (this.money1 == "" && this.money2 != "") {
          query.big = this.money2;
        } else if (this.money1 > this.money2) {
          let money = this.money2;
          this.money2 = this.money1;
          this.money1 = money;
          query.small = this.money1;
          query.big = this.money2;
        } else if (this.money1 != "" && this.money2 != "") {
          query.small = this.money1;
          query.big = this.money2;
        }
      } else if (this.type == "商品名") {
        if (this.searchVal !== "") query.name = this.searchVal;
      } else {
        if (this.searchVal !== "") query.type = this.searchVal;
      }
      return query;
    },
    goQuery() {
      let query = this.makePendingQuery();
      this.axios
          .get("/api/goods/get", {
            params: {
              ...query
            }
          })
          .then(res => {
            if (res.data.success) {
              var results = res.data;
              this.tableData = results.data;
              this.total = results.total;
              for (let i in this.tableData) {
                this.$set(this.tableData[i], "collect", false);
              }
              return this.axios.get("/api/collect/get", {
                params: {
                  username: this.$store.state.username,
                  type:"good"
                }
              });
            }
          })
          .then(res => {
            if (res.data.success) {
              var results = res.data.data;
              this.collectObs = results
                  .filter(item => item.status == "saling")
                  .map(item => {
                    return item.goodid;
                  });
              this.tableData.filter(item => {
                if (this.collectObs.includes(item.goodid)) {
                  item.collect = true;
                  return this.collectObs.includes(item.goodid);
                }
              });
            }
          });
    },
    goSearch() {
      this.pageNo = 1;
      this.goQuery();
    },
    goAddShop(row) {
      this.$prompt("请输入数量:", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^\d+$/, // 正则表达式，确保输入为数字
        inputErrorMessage: "请输入有效的数量"
      })
          .then(({ value }) => {
            const num = parseInt(value);
            if (num <= 0) {
              this.$message.error("请输入有效的数量");
              return;
            }
            this.axios
                .post("/api/shopcar/add", {
                  goodid: row.goodid,
                  username: this.$store.state.username,
                  num: num // 将数量传递给后端
                })
                .then(res => {
                  if (res.data.success) {
                    this.$message.success("成功加入购物车！");
                  } else {
                    this.$message.warning(res.data.message); // 直接使用后端返回的消息
                  }
                });
          })
          .catch(() => {});
    },
    change() {
      this.money1 = "";
      this.money2 = "";
      this.searchVal = "";
    },
    goCollect(row) {
      const type = "good";
      this.axios
          .post("/api/collect/add", {
            username: this.$store.state.username,
            goodid: row.goodid,
            status:row.status,
            type: type
          })
          .then(res => {
            if (res.data.success) {
              row.collect = true;
              this.$message.success("加入收藏!");
            }else {
              this.$message.error(res.data.message || "收藏失败");
            }
          })
          .catch(error => {
            this.$message.error(error.message || "请求失败，请重试！");
          });
    },
    goNoCollect(row) {
      const username = this.$store.state.username;
      const goodid = row.goodid;
      console.log(`Deleting collect for username: ${username}, goodid: ${goodid}`);
      this.axios
          .delete(`/api/collect/delete/good?username=${username}&goodid=${goodid}`)
          .then(res => {
            if (res.data.success) {
              row.collect = false;
              this.$message.success("取消收藏!");
            }
          })
          .catch(error => {
            console.error("Error while deleting collect:", error);
            this.$message.error("取消收藏失败!");
          });
    },
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 0;
      this.goQuery();
    },
    currentChangeHandle(val) {
      this.pageNo = val-1;
      this.goQuery();
    }
  }
};
</script>

<style scoped>
.width200 {
  width: 200px;
}
.inputwidth {
  height: 32px;
  line-height: 32px;
  width: 70px;
}
.goods-button-box {
  padding: 0 10px 10px 0;
  text-align: right;
}
.goods-card {
  margin-right: 40px;
  margin-top: 40px;
}
.goods-title {
  font-size: 13px;
  display: block;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.goods-image {
  width: 100%;
  height: 160px;
  display: block;
}
.goods-money {
  display: block;
  color: #f40;
  padding: 10px 0 0 10px;
}
.goods-search {
  width: 200px;
  margin-right: 10px;
}
.goods-num {
  text-align: right;
  display: block;
  color: #999;
  padding-right: 10px;
}
.goods-card-box {
  width: 300px;
  text-align: center;
  margin: 50px auto;
}
</style>
